﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace docmgr.WinForm
{
    public partial class PopWindow : Form
    {
        docmgr.BLL.Document docbll = new BLL.Document();
        docmgr.BLL.User userbll = new BLL.User();
        docmgr.BLL.DocReadLog drlbll = new BLL.DocReadLog();

        docmgr.BLL.Department depbll = new BLL.Department();
        public string code;//唯一编码。

        DataTable dt;//当前 文档信息。

        public int DocID;
        public PopWindow()
        {
            InitializeComponent();
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));

        }

        private void PopWindow_Load(object sender, EventArgs e)
        {

            if (Convert.ToInt32(Common.curUser.Rows[0]["PositionID"])!=1)
            {

                groupBox3.Visible = false;
            }
            dt = SQLHelper.ExecuteDataSet(SQLHelper.connString, "SELECT dh.Status,dh.id DHID, doc.ID, dh.HandlerUserID, doc.DocName,doc.UserID,doc.DocType FROM DocHandler as dh LEFT JOIN Document as doc on doc.ID=dh.DocID where dh.code='" + code + "'").Tables[0];
            if (dt.Rows.Count != 1)
            {
                MessageBox.Show("数据库不存在相关文件记录！");
                this.Close();
                return;
            }
            else
                DocID = Convert.ToInt32(dt.Rows[0]["ID"].ToString());


            button3.Visible = false;
            if (Convert.ToInt32(Common.curUser.Rows[0]["ID"]) == Convert.ToInt32(dt.Rows[0]["HandlerUserID"]))
            {
                //持有人ID
                
            }
            

            if (Convert.ToInt32(Common.curUser.Rows[0]["ID"]) == Convert.ToInt32(dt.Rows[0]["UserID"]) && dt.Rows[0]["DocType"].ToString().Equals("白头文件"))
            {
                button3.Visible = true;//如果白头文件，并且是自己创建的，可以随意。
            }

            if (Convert.ToInt32(Common.curUser.Rows[0]["PositionID"]) == 1)
            {
                //持有人ID
                button3.Visible = true;//如果是管理员，一切ok。全部可以销毁。
            }

            if (Convert.ToString(dt.Rows[0]["Status"])=="销毁")
            {
                MessageBox.Show("已销毁文件禁止操作!");
                this.Close();
                return;
            }
            this.label1.Text = (string)dt.Rows[0]["DocName"];

            comboBox2.DataSource = depbll.GetList("1=1");
            comboBox2.DisplayMember = "Name";
            comboBox2.ValueMember = "ID";

            doInit();

        }

        private void doInit()
        {
            int key = DocID;

            String sqlStr = String.Format("SELECT dbo.Document.DocName 文件名, dbo.[User].Name 转发人,drl.StartDate 转发日,u.name 批阅人,drl.ReadDate 批阅日期,  drl.Status 状态,drl.Comments 意见 FROM dbo.DocReadLog AS drl left JOIN dbo.[User] ON drl.LeaderId = dbo.[User].ID left JOIN dbo.Document ON drl.DocumentID = dbo.Document.ID     LEFT JOIN [User] as u on drl.ReadUserID= u.ID  where drl.DocumentID={0} order by drl.id desc", key);

            dataGridView2.DataSource = SQLHelper.ExecuteDataSet(SQLHelper.connString, sqlStr).Tables[0];

            sqlStr = String.Format("select count(*) c from DocReadLog as drl where status='已读' and drl.DocumentID={0}", key);
            label9.Text = "批阅次数:0";
            try
            {
                label9.Text = "批阅次数:" + Convert.ToInt32(SQLHelper.ExecuteDataSet(SQLHelper.connString, sqlStr).Tables[0].Rows[0]["c"]);
            }
            catch (Exception ee1)
            {

            }
            sqlStr = String.Format("select count(*) c from( select count(*) c from DocReadLog as drl where status='已读' and drl.DocumentID={0} group by ReadUserID) as cc", key);
            label8.Text = "批阅人数:0";
            try
            {
                label8.Text = "批阅人数:" + Convert.ToInt32(SQLHelper.ExecuteDataSet(SQLHelper.connString, sqlStr).Tables[0].Rows[0]["c"]);
            }
            catch (Exception ee2)
            {

            }
            sqlStr = String.Format("select count(*) c from (select count(*) c from DocReadLog as drl where status='未读' and drl.DocumentID={0} group by ReadUserID) as cc", key);
            label7.Text = "尚未批阅人数:0";
            try
            {
                label7.Text = "尚未批阅人数:" + Convert.ToInt32(SQLHelper.ExecuteDataSet(SQLHelper.connString, sqlStr).Tables[0].Rows[0]["c"]);
            }
            catch (Exception ee3)
            {

            }
            sqlStr = String.Format("SELECT doc.DocName 文件名,dc.Code 编码, u.Name 持有人, dc.Status 状态, dc.SysSerialNumber 卷号  FROM dbo.DocHandler AS dc INNER JOIN dbo.[User] AS u ON dc.HandlerUserID = u.ID INNER JOIN dbo.Document AS doc ON dc.DocID = doc.ID WHERE dc.DocID = {0} ORDER BY dc.ID DESC ", key);

            dataGridView3.DataSource = SQLHelper.ExecuteDataSet(SQLHelper.connString, sqlStr).Tables[0];
        }
        /// <summary>
        /// 做人呢，最重要的是要淡定，不要不开心。呵呵哈哈。是等太阳升起，还是等意外来临。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {   //批阅，增加一条阅读记录
            //并且使得所有的阅读题型设置为已读

            if(Commentstbx.Text=="")
            {
                MessageBox.Show("请填写批阅意见");
                return;
            }
            InputMessagebox frm = new InputMessagebox();
            if(Common.sessionLogin!=true)frm.ShowDialog();
            int userid=Convert.ToInt32(Common.curUser.Rows[0]["ID"]);

            int DocumentID = Convert.ToInt32(dt.Rows[0]["ID"]);
            DataTable tpdt = drlbll.GetList(String.Format(" Status='未读' and  DocumentID={0} and ReadUserID = {1}", DocumentID, userid));

            if (Common.sessionLogin == true||Common.EncryptCode(frm.password) == (string)Common.curUser.Rows[0]["Password"])
            {
                
                if(tpdt.Rows.Count!=0)
                {
                    for(int i=0;i<tpdt.Rows.Count;i++)
                    {
                        tpdt.Rows[i]["Status"] = "已读";
                        tpdt.Rows[i]["ReadDate"] = DateTime.Now.ToString();
                        tpdt.Rows[i]["Comments"] = Commentstbx.Text;
                    }
                    drlbll.Update(tpdt);
                }//更新所有提醒，表示已经阅读过
                else
                {
                    //若果没有相关记录，加一条就好了。
                    String fileds = "DocumentID , LeaderId, StartDate,Status,ReadDate,ReadUserID,Comments";

                    int LeaderId = userid;
                    string StartDate = DateTime.Now.ToString();
                    string ReadDate = StartDate;
                    string Status = "已读";
                    int ReadUserID = userid;
                    String Comments = Commentstbx.Text;


                    string sqlStr = String.Format("insert [DocReadLog] ( {0} ) values ({1},{2},'{3}','{4}','{5}',{6},'{7}')", fileds, DocumentID, LeaderId, StartDate, Status, ReadDate, ReadUserID, Comments);

                    SQLHelper.ExecuteSql(SQLHelper.connString, sqlStr);
                }
                MessageBox.Show("审阅成功！");
                frm.Dispose();
                this.Close();
            }
            else
            {
                MessageBox.Show("口令与当前用户不符！");
                frm.Dispose();
                this.Close();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //批阅，增加一条阅读记录
            //并且使得所有的阅读题型设置为已读
            if (Commentstbx.Text == "")
            {
                MessageBox.Show("请填写批阅意见");
                return;
            }
            InputMessagebox frm = new InputMessagebox();
            if (Common.sessionLogin != true) frm.ShowDialog();
            int userid = Convert.ToInt32(Common.curUser.Rows[0]["ID"]);

            int DocumentID = Convert.ToInt32(dt.Rows[0]["ID"]);
            DataTable tpdt = drlbll.GetList(String.Format(" Status='未读' and  DocumentID={0} and ReadUserID = {1}", DocumentID, userid));

            if (Common.sessionLogin == true||Common.EncryptCode(frm.password) == (string)Common.curUser.Rows[0]["Password"])
            {

                if (tpdt.Rows.Count != 0)
                {
                    for (int i = 0; i < tpdt.Rows.Count; i++)
                    {
                        tpdt.Rows[i]["Status"] = "已读";
                        tpdt.Rows[i]["ReadDate"] = DateTime.Now.ToString();
                        tpdt.Rows[i]["Comments"] = Commentstbx.Text;
                    }
                    drlbll.Update(tpdt);
                }//更新所有提醒，表示已经阅读过
                else
                {
                    //若果没有相关记录，加一条就好了。
                    String fileds = "DocumentID , LeaderId, StartDate,Status,ReadDate,ReadUserID,Comments";

                    int LeaderId = userid;
                    string StartDate = DateTime.Now.ToString();
                    string ReadDate = StartDate;
                    string Status = "已读";
                    int ReadUserID = userid;
                    String Comments = Commentstbx.Text;


                    string sqlStr = String.Format("insert [DocReadLog] ( {0} ) values ({1},{2},'{3}','{4}','{5}',{6},'{7}')", fileds, DocumentID, LeaderId, StartDate, Status, ReadDate, ReadUserID, Comments);

                    SQLHelper.ExecuteSql(SQLHelper.connString, sqlStr);
                }
                //dt.Rows[0]["HandleUserID"] = Common.curUser.Rows[0]["ID"];
                String Status1 = "在库";/**这个需要根据角色权限判断一下，目前先写死，一律写为在库*/
                if (Convert.ToInt32(Common.curUser.Rows[0]["PositionID"]) != 1)
                    Status1 = "传阅";//如果不是管理员状态，则是传阅。
                /*dt.Rows[0]["Status"] = Status1;
                docbll.Update(dt);*/
                SQLHelper.ExecuteSql(SQLHelper.connString, String.Format("update [DocHandler] set HandlerUserID={0},Status='{1}' where code ='{2}'", Convert.ToInt32(Common.curUser.Rows[0]["ID"]), Status1,code));
                MessageBox.Show("接受并批阅成功！");
                frm.Dispose();
                this.Close();
            }
            else
            {
                MessageBox.Show("口令与当前用户不符！");
                frm.Dispose();
                this.Close();
            }
        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            //流转
            InputMessagebox frm = new InputMessagebox(true);
            frm.ShowDialog();
            String sqlstr=String.Format("select * from [User] where ID={0} and Password='{1}'", Convert.ToInt32(comboBox1.SelectedValue), Common.EncryptCode(frm.password));
            DataTable d = SQLHelper.ExecuteDataSet(SQLHelper.connString, sqlstr).Tables[0];

            if (d.Rows.Count==1)
            {
                String status = "在库";

                if (Convert.ToInt32(d.Rows[0]["PositionID"]) != 1)
                    status = "传阅";
                SQLHelper.ExecuteSql(SQLHelper.connString, String.Format("update [DocHandler] set HandlerUserID={0} , Status= '{1}' where code= '{2}'", Convert.ToInt32(comboBox1.SelectedValue),status, code));
                MessageBox.Show("流转成功");
                frm.Dispose();
                this.Close();
            }
            else
            {
                MessageBox.Show("口令与当前用户不符！");
                frm.Dispose();
                this.Close();
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            //销毁
            InputMessagebox frm = new InputMessagebox();
            if (Common.sessionLogin != true) frm.ShowDialog();
            if (Common.sessionLogin == true || Common.EncryptCode(frm.password) == (string)Common.curUser.Rows[0]["Password"])
            {
                SQLHelper.ExecuteSql(SQLHelper.connString, String.Format("update [DocHandler] set status='销毁',HandlerUserID={0} where code= '{1}'",Convert.ToInt32(Common.curUser.Rows[0]["ID"]) ,code));

                MessageBox.Show("销毁成功");
                frm.Dispose();
                this.Close();
            }
            else
            {
                MessageBox.Show("口令与当前用户不符！");
                frm.Dispose();
                this.Close();
            }
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void comboBox2_SelectedValueChanged(object sender, EventArgs e)
        {
           
        }

        private void comboBox2_SelectionChangeCommitted(object sender, EventArgs e)
        {
            //部门相关的。
            try
            {
                comboBox1.DataSource = SQLHelper.ExecuteDataSet(SQLHelper.connString, String.Format("select ID,Name from [user] where DepartmentID = {0}", Convert.ToInt32(comboBox2.SelectedValue))).Tables[0];
                comboBox1.DisplayMember = "Name";
                comboBox1.ValueMember = "ID";

            }
            catch (Exception ex11)
            {
            }
            finally
            {
                
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if(textBox1.Text=="")
            {
                MessageBox.Show("卷号不能为空!");
                return;
            }
            try
            {
                SQLHelper.ExecuteSql(SQLHelper.connString, String.Format("update [DocHandler] set status='存档',HandlerUserID={0},SysSerialNumber='{1}' where code= '{2}'", Convert.ToInt32(Common.curUser.Rows[0]["ID"]), textBox1.Text, code));
            }
            catch(Exception ex11)
            {
                Console.WriteLine(ex11.StackTrace);
                
            }
            finally
            {
                MessageBox.Show("存档成功");
            }
            this.Close();
        }
    }
}
